package com.fengbaogu.handlers;
import java.net.SocketAddress;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.fengbaogu.bean.MyMap;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Component
@Qualifier("serverHandler")
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

	private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
	
	@Override
	public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		//处理换行
		msg=msg.substring(0, msg.length()-2);
		if(msg.startsWith("s"))
		{
			//注册
			MyMap.getInstance().getAddress().put(ctx.channel().remoteAddress(), msg);
			MyMap.getInstance().getChannels().put(msg,ctx.channel());
		//	address.put(ctx.channel().remoteAddress(), msg);
	//		channels.put(msg,ctx.channel());
			System.out.print(msg+"注册成功! 当前在线人数:"+MyMap.getInstance().getChannels().size()+"---------------");
		}
		ctx.channel().writeAndFlush("你说:"+msg+"\r\n");
		
		for (Entry<SocketAddress, String> entry : MyMap.getInstance().getAddress().entrySet()) {
		    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
		} 
		super.channelActive(ctx);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
//        ctx.channel().writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
        ctx.channel().writeAndFlush( "success\n");
		super.channelActive(ctx);
	}
	
	/**
	 * 异常关闭
	 */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//    	System.out.println(address.get(ctx.channel().remoteAddress())+"异常下线了  当前在线人数:"+channels.size()+"--------------------");
//    	channels.remove(address.get(ctx.channel().remoteAddress()));
//    	address.remove(ctx.channel().remoteAddress());
    	cause.notify();
        ctx.close();
    }
    
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//		System.out.println(address.get(ctx.channel().remoteAddress())+"正常下线了  当前在线人数:"+channels.size()+"--------------------");
//    	channels.remove(address.get(ctx.channel().remoteAddress()));
//    	address.remove(ctx.channel().remoteAddress());
        ctx.close();
		//log.info("\nChannel is disconnected");
		//super.channelInactive(ctx);
	}
	
	/**
	 * 主动发消息
	 */
public void sendMessage(String shopid,String mess)
{
    Map<String, Channel> channels = MyMap.getInstance().getChannels();
	channels.get("s1").writeAndFlush(mess+ "\r\n");
}

}